package com.lebang.medicalInquiry.component;

import com.lebang.medicalInquiry.initializer.ServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @version V1.0
 * @author: zpc
 * @date:
 */
@Component
public class NettyComponent {

    @Autowired
    private ServerInitializer serverInitializer;

    public void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup work = new NioEventLoopGroup();
        try {

            ChannelFuture bind = new ServerBootstrap()
                    .group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    //SO_BACKLOG 控制全连接队列的大小  也就是控制 允许多少链接
                    .option(ChannelOption.SO_BACKLOG, 1)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(serverInitializer).bind(7902).sync();

            bind.channel().closeFuture().await();
        } catch (
                Exception e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
